<template>
	<view class="home">
		<custom-navbar title="我的金融" :show-back="true" @back="handleBack" />

		<view class="content" :style="{ paddingTop: navBarHeight + 'px' }">
			<!-- 分类选项卡 -->
			<view class="search p0030">
				<view class="flex">
					<view v-for='(item,index) in financeCategories' :key="index" class="typelist fcolcc"
						:style="{ marginRight: index < financeCategories.length - 1 ? '67rpx' : '0' }">
						<view class="f30bc3" :class="finance_category == item.value ? 'c398DFB' : ''"
							@click="switchFinanceCategory(item.value)">
							{{item.label}}
						</view>
						<view v-if="finance_category == item.value" class="underline"></view>
					</view>
				</view>
			</view>

			<!-- 空状态 -->
			<view v-if="isEmpty" class="empty-state fcolcc">
				<image class="empty-image" src="/static/images/common/empty.png"></image>
				<view class="empty-text">暂无金融产品数据</view>
				<up-button type="primary" shape="circle" @click="loadFinanceList(true)"
					style="width: 200rpx;margin-top: 30rpx;">
					重新加载
				</up-button>
			</view>

			<!-- 金融产品列表 -->
			<view v-else class="p30">
				<view class="list">
					<view class="item p4030 mb20" v-for="(item,index) in financeList" :key="index"
						@click="handleProductClick(item)">
						<!-- 添加右上角状态标签 -->
						<view class="status-tag" v-if="item.remaining_time_text">
							进行中 | 剩余{{ item.remaining_time_text }}天
						</view>
						<view class="f306c3 mb18">{{item.finance_title}}</view>
						<view class="fc mb35">
							<view v-for="(tag,tagIndex) in item.product_tags_text" :key="tagIndex"
								class="p0020 fcc tips mr10">
								{{tag}}
							</view>
						</view>
						<view class="f22c9">{{item.institution_name || '区金融发展服务中心'}}</view>
						<up-line margin='12rpx 0 30rpx 0'></up-line>
						<view class="fcsb">
							<view class="f22c9">起止时间:{{formatDate(item.start_time)}}至{{formatDate(item.end_time)}}
							</view>
							<image class="wh36"
								:src="item.is_collection == 1 ? '/static/images/talents/已收藏.svg' : '/static/images/talents/未收藏.svg'"
								@click="toggleCollection(item)">
							</image>
						</view>
					</view>
				</view>
			</view>

			<!-- 加载更多 -->
			<view v-if="isLoadingMore" class="loading-more fcc">
				<up-loading-icon text='加载中...'></up-loading-icon>
			</view>
			<view v-if="noMoreData" class="no-more fcc">
				没有更多数据了
			</view>
		</view>
	</view>
</template>

<script setup>
	import CustomNavbar from '@/components/custom-navbar.vue'
	import {
		ref,
		onMounted,
		computed
	} from 'vue';
	import {
		onReachBottom
	} from '@dcloudio/uni-app'
	import {
		myFinance
	} from '@/api/user'
	import {
		getClassification
	} from '@/api/login'

	// 系统信息
	const systemInfo = uni.getSystemInfoSync()
	const navBarHeight = computed(() => systemInfo.statusBarHeight + 44)

	// 数据状态
	const isLoading = ref(false)
	const isLoadingMore = ref(false)
	const noMoreData = ref(false)
	const isEmpty = ref(false)

	// 分页参数
	const page = ref(1)
	const limit = ref(10)
	const total = ref(0)

	// 金融分类
	const financeCategories = ref([])
	const finance_category = ref('')

	// 金融产品列表
	const financeList = ref([])

	// 初始化加载
	onMounted(() => {
		loadFinanceCategories()
	})

	// 加载金融分类
	const loadFinanceCategories = async () => {
		try {
			const res = await getClassification(5)
			if (res.code === 200) {
				financeCategories.value = res.data
				if (financeCategories.value.length > 0) {
					finance_category.value = financeCategories.value[0].value
					loadFinanceList(true)
				}
			}
		} catch (error) {
			console.error('加载金融分类失败:', error)
			uni.showToast({
				title: '加载分类失败',
				icon: 'none'
			})
		}
	}

	// 加载金融产品列表
	const loadFinanceList = async (isRefresh = false) => {
		if (isLoading.value && !isRefresh) return

		try {
			if (isRefresh) {
				page.value = 1
				noMoreData.value = false
				isLoading.value = true
			} else {
				isLoadingMore.value = true
			}

			const params = {
				finance_category: finance_category.value,
				page: page.value,
				limit: limit.value
			}

			const res = await myFinance(params)

			if (res.code === 200) {
				if (isRefresh) {
					financeList.value = res.data.data
					total.value = res.data.total
				} else {
					financeList.value = [...financeList.value, ...res.data.data]
				}

				// 检查是否还有更多数据
				if (res.data.data.length < limit.value) {
					noMoreData.value = true
				}

				// 检查空状态
				isEmpty.value = financeList.value.length === 0
			}
		} catch (error) {
			console.error('加载金融产品列表失败:', error)
			uni.showToast({
				title: '加载失败，请重试',
				icon: 'none'
			})
		} finally {
			isLoading.value = false
			isLoadingMore.value = false
		}
	}

	// 切换金融分类
	const switchFinanceCategory = (category) => {
		if (finance_category.value === category) return
		finance_category.value = category
		loadFinanceList(true)
	}

	// 格式化日期
	const formatDate = (dateString) => {
		if (!dateString) return ''
		const date = new Date(dateString)
		return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
	}

	// 收藏/取消收藏
	const toggleCollection = (item) => {
		// 这里调用收藏/取消收藏的接口
		// 示例代码，需要根据实际接口实现
		item.is_collection = item.is_collection == 1 ? 0 : 1
		uni.showToast({
			title: item.is_collection == 1 ? '已收藏' : '已取消收藏',
			icon: 'none'
		})
	}

	// 返回
	const handleBack = () => {
		uni.navigateBack()
	}
	// 点击产品
	const handleProductClick = (item) => {
		console.log('点击了金融产品:', item);
		uni.navigateTo({
			url: `/pages/financing/product?finance_id=${item.finance_id}`
		})

	};
	// 加载更多
	onReachBottom(() => {
		if (isLoadingMore.value || noMoreData.value) return
		page.value += 1
		loadFinanceList()
	})
</script>

<style lang="scss" scoped>
	.home {
		width: 100%;
		min-height: 100vh;
		background-color: #f7f7f7;

		.content {
			padding-top: var(--status-bar-height);
			padding-top: calc(var(--status-bar-height) + 70rpx);

			.search {
				background: #FFFFFF;
				padding: 16rpx 30rpx 24rpx 30rpx;

				.typelist {
					position: relative;

					.underline {
						width: 40rpx;
						height: 4rpx;
						background: #398DFB;
						border-radius: 500rpx;
						position: absolute;
						bottom: -23rpx;
					}
				}
			}

			.empty-state {
				height: 60vh;
				padding: 40rpx;
				text-align: center;

				.empty-image {
					width: 300rpx;
					height: 300rpx;
					margin-bottom: 30rpx;
				}

				.empty-text {
					font-size: 28rpx;
					color: #999;
				}
			}

			.list {
				.item {
					width: 100%;
					background: #FFFFFF;
					border-radius: 20rpx;
					border: 1rpx solid;
					border-image: linear-gradient(61deg, rgba(57, 141, 251, 0), rgba(255, 255, 255, 1)) 1 1;
					position: relative;

					/* 为绝对定位的status-tag提供定位上下文 */
					.status-tag {
						position: absolute;
						top: 0;
						right: 0;
						width: 205rpx;
						height: 51rpx;
						background: #398DFB;
						border-radius: 0rpx 20rpx 0rpx 20rpx;
						color: #FFFFFF;
						font-size: 24rpx;
						display: flex;
						justify-content: center;
						align-items: center;
					}

					.f306c3 {
						font-size: 30rpx;
						font-weight: bold;
						color: #6c6c6c;
					}

					.tips {
						height: 44rpx;
						background: rgba(57, 141, 251, 0.1);
						border-radius: 8rpx;
						font-size: 20rpx;
						color: #398DFB;
						line-height: 44rpx;
						padding: 0 20rpx;
					}

					.f22c9 {
						font-size: 22rpx;
						color: #999;
					}

					.wh36 {
						width: 36rpx;
						height: 36rpx;
					}
				}
			}

			.loading-more,
			.no-more {
				padding: 30rpx 0;
				color: #999;
				font-size: 26rpx;
			}
		}
	}

	.flex {
		display: flex;
	}

	.fcolcc {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}

	.fcsb {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.fc {
		display: flex;
		align-items: center;
	}

	.fcc {
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.p0030 {
		padding: 0 30rpx;
	}

	.p30 {
		padding: 30rpx;
	}

	.mb18 {
		margin-bottom: 18rpx;
	}

	.mb20 {
		margin-bottom: 20rpx;
	}

	.mb35 {
		margin-bottom: 35rpx;
	}

	.mr10 {
		margin-right: 10rpx;
	}

	.f30bc3 {
		font-size: 30rpx;
		font-weight: bold;
		color: #333;
	}

	.c398DFB {
		color: #398DFB;
	}
</style>